<template>
  <el-empty style="height: 80vh" v-if="showEmpty">
    <template #description>
      <span v-if="getToken()" style="color: #909399"
        >您没有被授权学习任何课程</span
      >
      <to-login v-else icon="HomeFilled" text="请先登录" path="/login" />
    </template>
  </el-empty>
  <div v-else>
    <div ref="my_breadCrumb" class="breadcrumb">
      <span>所选课程：</span>
      <template v-for="(item, index) in breadcrumbs" :key="index">
        <span class="breadcrumb-item" @click="handleBreadcrumbClick(index)">{{
          item.name
        }}</span>
        <span v-if="index < breadcrumbs.length - 1" class="separator">/</span>
      </template>
    </div>
    <div
      ref="my_line"
      style="
        height: 1px;
        width: 95%;
        background-color: #dcdfe6;
        margin: 10px auto;
      "
    />
    <!-- 卡片列表 -->
    <el-row :gutter="30" v-if="table.length > 0">
      <el-col :span="8" v-for="item in table" :key="item.id">
        <div class="card-wrapper">
          <el-card class="subject-card" :body-style="{ padding: '0px' }">
            <img :src="item.cover" class="image" :alt="item.name" />
            <div class="card-content">
              <h3>{{ item.name }}</h3>
              <p class="description">{{ item.description }}</p>
              <div class="info">
                <span>时长: {{ item.duration }}分钟</span>
                <el-button
                  @click="handleStart(item)"
                  type="primary"
                  size="small"
                  >开始学习</el-button
                >
              </div>
            </div>
          </el-card>
        </div>
      </el-col>
      <el-pagination
        style="margin: auto"
        v-if="showPagination"
        background
        layout="prev, pager, next"
        :page-count="pageCount"
        :current-page="currentPage"
        @current-change="handleCurrentChange"
      />
    </el-row>
    <!-- 空状态显示 -->
    <TrainingDetail v-else :showTrainingDetail="showTrainingDetail" />
  </div>
</template>

<script setup>
import TrainingDetail from "@/components/trainingDetail.vue";
import { ref, onMounted, watch, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useStore } from "vuex";
import subjectApi from "@/api/subject/index";
import { getToken } from "@/utils/auth"; // get token from cookie
import ToLogin from "@/components/toLogin.vue";
import host from "@/utils/host";

const currentPage = ref(1);
const pageSize = ref(6);
const pageCount = ref(0);
const showPagination = ref(false);

const handleCurrentChange = (page) => {
  currentPage.value = page;
  initFromRoute();
};

const router = useRouter();
const route = useRoute();
const store = useStore();
const my_breadCrumb = ref(null);
const my_line = ref(null);
const showTrainingDetail = ref({});
const showEmpty = ref(false);

const table = ref([]);
// 使用 computed 从 Vuex 获取 breadcrumbs
const breadcrumbs = computed(() => store.getters.breadcrumbs);

// 从路由参数初始化面包屑
const initFromRoute = async () => {
  // 检查是否需要重置面包屑
  if (route.query.resetBreadcrumbs === "true") {
    store.dispatch("learn/setBreadcrumbs", [{ name: "全部课程", id: null }]);
    await getSubject();
    // 清除重置参数
    router.replace({
      query: {},
    });
    return;
  }

  // 如果有路由参数，优先使用路由参数
  const { path = "", names = "" } = route.query;
  if (path && names) {
    const pathArr = path.split(",");
    const nameArr = names.split(",");

    const newBreadcrumbs = [{ name: "全部课程", id: null }];

    // 重建面包屑路径
    for (let i = 0; i < pathArr.length; i++) {
      if (pathArr[i] !== "null") {
        newBreadcrumbs.push({
          id: Number(pathArr[i]),
          name: decodeURIComponent(nameArr[i]),
        });

        // 获取最后一级的数据
        if (i === pathArr.length - 1) {
          const res = await subjectApi.getByParentId(
            Number(pathArr[i]),
            currentPage.value,
            pageSize.value
          );
          if (res.data.records.length > 0) {
            table.value = res.data.records;
            pageCount.value = res.data.pages;
            showPagination.value = true;
          } else {
            const res = await subjectApi.getSubjectMapById(Number(pathArr[i]));
            showTrainingDetail.value = res.data;
          }
          store.dispatch("learn/setBreadcrumbs", newBreadcrumbs);
          return;
        }
      }
    }
  }
  // 如果没有路由参数但有保存的breadcrumbs状态，使用最后一级的id获取数据
  else if (store.getters.breadcrumbs.length > 1) {
    const lastBreadcrumb =
      store.getters.breadcrumbs[store.getters.breadcrumbs.length - 1];
    if (lastBreadcrumb.id !== null) {
      const res = await subjectApi.getByParentId(
        lastBreadcrumb.id,
        currentPage.value,
        pageSize.value
      );
      if (res.data.records.length > 0) {
        table.value = res.data.records;
        pageCount.value = res.data.pages;
        showPagination.value = true;
      } else {
        const res = await subjectApi.getSubjectMapById(lastBreadcrumb.id);
        showTrainingDetail.value = res.data;
      }
      return;
    }
  }

  // 如果没有路由参数也没有保存的状态，获取根目录数据
  await getSubject();
};

const handleStart = async (item) => {
  const res = await subjectApi.getByParentId(
    item.id,
    currentPage.value,
    pageSize.value
  );
  table.value = [];
  const newBreadcrumbs = [
    ...breadcrumbs.value,
    { name: item.name, id: item.id },
  ];
  store.dispatch("learn/setBreadcrumbs", newBreadcrumbs);

  if (res.data.records.length > 0) {
    table.value = res.data.records;
    pageCount.value = res.data.pages;
    showPagination.value = true;
  }
  updateRoute();
};

const handleBreadcrumbClick = async (index) => {
  if (index === breadcrumbs.value.length - 1) return;

  const newBreadcrumbs = breadcrumbs.value.slice(0, index + 1);
  store.dispatch("learn/setBreadcrumbs", newBreadcrumbs);

  const currentItem = breadcrumbs.value[index];
  if (currentItem.id === null) {
    await getSubject();
  } else {
    const res = await subjectApi.getByParentId(
      currentItem.id,
      currentPage.value,
      pageSize.value
    );
    table.value = res.data.records;
    pageCount.value = res.data.pages;
    showPagination.value = true;
  }
  updateRoute();
};

// 更新路由参数
const updateRoute = () => {
  // 跳过第一个"全部课程"项
  const pathArr = breadcrumbs.value.slice(1);
  const path = pathArr.map((item) => item.id).join(",");
  const names = pathArr.map((item) => encodeURIComponent(item.name)).join(",");

  router.replace({
    query: {
      ...route.query,
      path: path || "null",
      names: names || "全部课程",
    },
  });
};

const getSubject = async () => {
  const res = await subjectApi.getMySubjects();
  showPagination.value = false;
  table.value = res.data;
  if (table.value.length === 0) {
    showEmpty.value = true;
  } else {
    showEmpty.value = false;
  }
};

// 监听路由变化
watch(
  () => route.query,
  () => {
    initFromRoute();
  }
);

onMounted(async () => {
  if (getToken()) {
    await initFromRoute();
  } else {
    showEmpty.value = true;
  }
});
</script>

<style scoped>
.card-wrapper {
  padding: 10px;
}

.subject-card {
  margin-bottom: 30px;
  transition: all 0.3s;
}

.subject-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  display: block;
}

.card-content {
  padding: 14px;
  cursor: default;
}

.description {
  font-size: 14px;
  color: #666;
  margin: 10px 0;
}

.info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #999;
  font-size: 13px;
}

.breadcrumb {
  display: flex;
  align-items: center;
  padding: 20px 20px 0 20px;
}

.breadcrumb-item {
  color: #409eff;
  cursor: pointer;
  transition: color 0.3s;
}

.breadcrumb-item:hover {
  color: #66b1ff;
}

.separator {
  margin: 0 8px;
  color: #909399;
}
</style>
